﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DeStores.Common.DAL.Abstract;
using NHibernate;
using NHibernate.Cfg;

namespace DeStores.Common.DAL.Manager
{
    public class DBSesionFactory : IDBSesionFactory
    {
        #region Fields

        private ISessionFactory _sessionFactory = null;
        private readonly string _connectionString;
        private readonly string _configFileName;

        #endregion

        #region Constrctors

        public DBSesionFactory()
        {
            
        }

        public DBSesionFactory(string connectionString)
        {
            _connectionString = connectionString;
        }

        #endregion

        #region dd

        public ISession CreateSession()
        {
            if(this._sessionFactory == null)
            {
                this._sessionFactory = CreateSessionFactory();
            }
            return this._sessionFactory.OpenSession();
        }

        #endregion

        #region IDisposable members

        public void Dispose()
        {
            if(this._sessionFactory != null)
            {
                _sessionFactory.Dispose();
            }
        }

        #endregion

        #region Helpers

        private ISessionFactory CreateSessionFactory()
        {
            var configuration = new Configuration();
            configuration.Configure(this._configFileName);
            if (string.IsNullOrEmpty(this._connectionString))
            {
                configuration.SetProperty("connection.connection_string", _connectionString);
            }
            return configuration.BuildSessionFactory();
        }

        #endregion
    }
}

